<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Cache;
use App\Http\Controllers\Api\TimerController;

class DataUploadController extends Controller
{
    public function getTempHumPressure(Request $request) {
        info($request->all());
        //http://192.168.8.150/api/zbgw/dataUpload/getTempHumPressure?dev_num=1147724
        // http://192.168.8.150/api/sdzz/dataUpload/getTempHumPressure?dev_num=1166799
        $dev_num = $request->dev_num;
        $charset = $request->charset;
        try{
            $item = DB::table('a_hb6303')->where('dev_num', $dev_num)->first();
            if (isset($item->tcp_type) && $item->tcp_type == 'tcp server') {
                info("dataupload获取温湿度大气压");
                $timerCon = new TimerController();
                $timerCon->upEnv($item);
            }
        }catch(\Exception $exception){
            info("设备获取温湿度大气压失败：".$exception->getMessage());
        }
        $date = date('Y-m-d H:i:s', strtotime('-60 minute'));
        $data = DB::table('a_env_info')->where('dev_num', $dev_num)->where('time', '>', $date)->where('temp', '!=', '')->orderBy('id', 'desc')->first();

        $code = 'none';
        $temp = '';
        $humi = '';
        $pressure = '';
        $time = '';
        $pos = '';
        $yuliu1 = '';
        $yuliu2 = '';
        $yuliu3 = '';

        if($data !== null) {
            $pos = DB::table('a_hb6303')->where('dev_num', $dev_num)->value('pos');
            $pos = $pos == null ? "" : $pos;
            $code = 'success';
            $temp = $data->temp;
            $humi = $data->humi;
            $pressure = $data->pressure;
            $pressure = $pressure > 0 ? $pressure: DB::table('a_env_info')->where('pressure','>',0)->orderBy('id','desc')->value('pressure');
            $time = $data->time;
            if($charset) {
                $pos = iconv("utf-8", "{$charset}//IGNORE", $pos);
            }
        }
        $res = "{$code},{$temp},{$humi},{$pressure},{$time},{$pos},{$yuliu1},{$yuliu2},{$yuliu3}";
        info($res);
        header_remove();
        return $res;
    }

    /* 拉压力机 安全帽 数据上传 */
    public function LLJ_upload(Request $request, $strType = '') {
        // return "start{0}end";
        $arrRequest = $request->all();
        try{
            foreach($arrRequest as $k => &$vv) {
                $vv = iconv("gb2312", "utf-8//IGNORE", $vv);
            }
            unset($vv);  //去除$v的引用效果
        }catch(\Exception $e){
            info("错误：".$e->getLine().$e->getMessage());
        }

        if($strType == 'AQM') {
            info("AQM---DATA"); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
            info($arrRequest); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
        }
        else {
            info('拉压力机--数据上传'); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
            info($arrRequest); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
        }

        if (!$arrRequest) {
            return "start{2}end";
        }

        // info('LaLiJi--dataUpload');//该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
        // return "start{3}end"; // 此行代码为测试用--------============================
        //获取 sample_info 的 bar_code
        $bar_code = $arrRequest['bar_code'];
        $username = $arrRequest['username']; //工号

        /* $manager_id = DB::table('manager')->where('username', $username)->value('id');
        if (!$manager_id) {
            return "start{1}end"; //"工号 “{$工号}” 无效";
        } */

        $sample_info = DB::table('a_sample_info as a')
                         ->leftJoin('a_contract_gaiyao as b', 'a.contract_gaiyao_id', '=', 'b.id')
                         ->where('a.bar_code', $bar_code)
                         ->orWhere('a.third_id', $bar_code)
                         ->orderBy('a.id','desc')
                         ->select('a.*', 'b.tool_id', 'b.std_id', 'b.vol_id', 'b.class_id','b.tool_name')
                         ->first();
        if(!$sample_info) {
            return "start{2}end"; //"未受理条码为 “{$bar_code}” 的样品";
        }

        $str_item_ids = $request->item_id;
        $arr_item_id = explode(',', $str_item_ids); //字符串 --> 数组
        $item_data_info = DB::table('a_item_data')->where('sample_info_id', $sample_info->id)->whereIn('item_id', $arr_item_id)->first();
        if(!$item_data_info) {
            $arr_item_id2 = DB::table('a_testitem')->whereIn('id', $arr_item_id)->pluck('id_map')->toArray();
            $item_data_info = DB::table('a_item_data')->where('sample_info_id', $sample_info->id)->whereIn('item_id', $arr_item_id2)->first();
            if(!$item_data_info) {
                $arr_item_id2 = DB::table('a_testitem')->whereIn('id_map', $arr_item_id)->pluck('id')->toArray();
                $item_data_info = DB::table('a_item_data')->where('sample_info_id', $sample_info->id)->whereIn('item_id', $arr_item_id2)->first();
                if(!$item_data_info) {
                    return "start{3}end"; //"条码为 “{$bar_code}” 的样品，未受理此检测项目";
                }
            }
        }

        /* if ($manager_id !== $item_data_info->manager_id) {
            return "start{4}end"; //此任务未分配给您
        } */
        //--------------------------------------------------------
        $item_data_id = $item_data_info->id; //a_item_data表的id
        
        $commit = $item_data_info->commit;
        if($commit > 0) {
            //如果该样品已提交，则不允许保存
            return "start{5}end"; // "条码为 “{$bar_code}” 的样品已提交，不允许上传";
        }

        //获取天气和大气压力
        //$myApiController = new \App\Http\Controllers\Admin\MyApiController();
        //$wea_json = $myApiController->getWeather();
        //$wea_str = $wea_json->getContent();
        //$wea_arr = json_decode($wea_str, true);


        /*//缓存温度 30min
        Cache::put('temp', $request->temp, 30);
        //缓存湿度 30min
        Cache::put('hum', $request->hum, 30); */

        $key_data = DB::table('a_testdata_key')->select('id','data_unit','data_key')->where([
            ['std_id', '=', $sample_info->std_id],
            ['tool_id', '=', $sample_info->tool_id],
            ['item_id', '=', $item_data_info->item_id]
        ])->orderBy('sort')->get();

        if($strType == 'AQM') {
            # 安全帽
            $itemId = $item_data_info->item_id;
            $testItem = DB::table('a_testitem')->where('id',$itemId)->first();
            $itemIdMap = data_get($testItem,'id_map',0) ?: $itemId;
            if(in_array($itemIdMap, [16,80])) {
                # 冲击
                $arr = [$request->strength_max];
            }
            else if(in_array($itemIdMap, [2,81])) {
                # 穿刺
                $arr = [$request->is_through == '1' ? '接触' : '未接触'];
            }
        }
        else {
            if (substr($request->device_num,0,3) == 'MTS') {
                $arrRequest['strength_keep'] *= 1000;
            }
            $arr = [$arrRequest['strength_keep'], $arrRequest['time_keep']];
        }

        //        info($arr); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
        if($arr) {
            # 判断$arr不是空数组，再进行以下操作
            foreach($key_data as $k => $v) {
                if($v->data_unit === 'min'){
                    if(isset($arr[1])){
                        $arr[1] = $arr[1]/60;
                    }
                }
                $input_data = DB::table('a_input_data')->where([
                    ['sample_info_id', '=', $sample_info->id],
                    ['testdata_key_id', '=', $v->id]
                ])->first();
                if($input_data) {
                    DB::table('a_input_data')->where('id', $input_data->id)->update(['val' => $arr[$k]]);
                }
                else {
                    //如果记录不存在，则插入
                    DB::table('a_input_data')->insert(
                        [
                            'sample_info_id'  => $sample_info->id,
                            'testdata_key_id' => $v->id,
                            'val'             => $arr[$k]
                        ]
                    );
                }

                if(count($arr) === $k + 1) {
                    break;
                }
            }
        }

        // 结论,0-不符合，1-符合，2-未录入
        if($arrRequest['res'] === '0' || $arrRequest['res'] === '1' || $arrRequest['res'] === '2') {
            $jielun = $arrRequest['res'];
        }
        else if($arrRequest['res'] === '合格') {
            $jielun = '1';
        }
        else if($arrRequest['res'] === '不合格') {
            $jielun = '0';
        }
        else {
            $itemDataController = new ItemDataController();
            $jielun = $itemDataController->getUploadRes2Res($sample_info,$item_data_info,$key_data,$arr);
        }

        $base64_img = str_replace(' ','+',data_get($arrRequest,'image','')) ;
        if ($base64_img) {
            $filename = "{$sample_info->tool_name}_波形图_{$bar_code}_{$item_data_id}"; //这里用item_data_id ,不能用item_id,否则可能会出现错误的可能
            $uploadcon = new UploadController();
            $res = $uploadcon->render('img', [
                'dir' => 'input_data',
                'file' => $base64_img,
                'filename' => $filename,
                'text' => $bar_code,
            ]);
            if($res['code'] == 1){
                $image = $res['data']['path'];
            }else{
                info('LLJ/AQM image error');info($res);
            }
        }
        $upItemdata = [
            'wea'      => $arrRequest['wea'],
            'pressure' => $request->pressure,
            'temp'     => $request->temp,
            'hum'      => $request->hum,
            'remark'   => $arrRequest['remark'],
            'res'      => $jielun,
            'utime'    => isset($request->test_date) ? $request->test_date : (isset($request->test_data) ? $request->test_data : '')
        ];
        if(isset($image)){
            // dd($image);
            $upItemdata['image'] = $image;
        }
        $res = DB::table('a_item_data')->where('id', $item_data_id)->update($upItemdata);
        $itemDataController = new ItemDataController();
        $itemDataController->updateStations($item_data_id,'',$request->device_num);
        $sample_info_id = $sample_info->id;
        $data_waiGuan = [
            'res' => '1', 'utime' => $upItemdata['utime']
        ];
        $itemDataController->waiGUanAutoFill($sample_info_id, $data_waiGuan);
        $itemDataController->updateJieLun($sample_info_id); //更新 a_sample_info 表的 结论
        $itemDataController->updateTester($sample_info_id); //更新 a_sample_info 表的 检验人员
        $itemDataController->updateTestTime_NextTime($sample_info_id); //更新 a_sample_info 表的 试验时间 和 下次试验时间
        return "start{0}end"; // 上传成功
    }


    /* 拉压力机 登录验证 */
    public function LLJ_login(Request $request) {
        $arrRequest = $request->all();
        foreach($arrRequest as $k => $v) {
            $arrRequest[$k] = iconv("gb2312", "utf-8//IGNORE", $v);
        }

        if($request->isMethod('POST') or true) {
            info('拉压力机--登录'); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
            info($arrRequest); //该方法会将日志全部记录在 storage/logs/laravel.log 文件里，这样的问题是当日志文件比较多的时候查找起来比较麻烦
            # 登录验证
            $username = $arrRequest['username'];
            $password2 = $arrRequest['password'];
            $res = DB::table('manager')->where(['password2' => $password2])->whereRaw('(num = ? or username = ?)', [$username,$username])->first();
            if($res) {
                # 验证通过
                $res = "start{0}end";
            }
            else {
                # 验证不通过
                $res = "start{1}end";
            }
            info($res);
            return $res;
        }
    }

    /* 安全帽 登录验证 */
    public function AQM_login(Request $request) {
        header_remove();
        header("Content-type: text/html; charset=utf-8");
        return $this->LLJ_login($request);
    }

    /* 安全帽 结果上传 */
    public function AQM_upload(Request $request) {
        header_remove();
        header("Content-type: text/html; charset=utf-8");
        return $this->LLJ_upload($request, 'AQM');
    }
}
